$(function () {
    let layer = layui.layer;
    let form = layui.form;
    initArtCateList();

    function initArtCateList() {
        $.ajax({
            method: 'GET',
            url: '/my/article/cates',
            success: function (res) {
                if (res.status !== 0) return layer.msg('获取文章分类失败');
                let htmlStr = template('tpl-table', res);
                $('tbody').html(htmlStr);
            }
        })
    }

    let indexAdd = null;
    $('#btnAddCate').on('click', function () {
        indexAdd = layer.open({
            type: 1,
            title: '添加文章分类',
            area: ['500px', '250px'],
            content: $('#dialog-add').html()
        });
    })

    $('body').on('submit', '#form-add', function (e) {
        e.preventDefault();
        $.ajax({
            method: 'POST',
            url: '/my/article/addcates',
            data: $(this).serialize(),
            success: function (res) {
                if (res.status !== 0) return layer.msg('新增分类失败');
                layer.msg('新增分类成功');
                initArtCateList();
                layer.close(indexAdd);
            }
        })
    })

    let indexEdit = null;
    $('tbody').on('click', '.btn-edit', function () {
        indexEdit = layer.open({
            type: 1,
            title: '修改文章分类',
            area: ['500px', '250px'],
            content: $('#dialog-edit').html()
        });

        //加data会加? /my/article/cates/?1
        let id = $(this).attr('data-id');
        $.ajax({
            method: 'GET',
            url: '/my/article/cates/' + id,
            success: function (res) {
                if (res.status !== 0) return layer.msg('根据id获取文章信息失败');
                form.val('form_edit', res.data);
            }
        })

    })

    $('body').on('submit', '#form-edit', function (e) {
        e.preventDefault();
        $.ajax({
            method: 'POST',
            url: '/my/article/updatecate',
            data: $(this).serialize(),
            success: function (res) {
                if (res.status !== 0) return layer.msg('修改分类失败');
                layer.msg('修改分类成功');
                layer.close(indexEdit);
                initArtCateList();
            }
        })
    })

    $('tbody').on('click', '.btn-delete', function () {
        let Id=$(this).attr('data-id');
        layer.confirm('确定删除吗?', {icon: 3, title:'提示'}, function(index){
            //do something
            
            $.ajax({
                method: 'GET',
                url: '/my/article/deletecate/'+Id,
                success: function (res) {
                    if (res.status !== 0) return layer.msg('删除分类失败');
                    layer.msg('删除分类成功');
                    layer.close(index);
                    initArtCateList();
                }
            })
            
          });

    })

})